﻿using System.Collections.Generic;
using TimeMachine.Engine.Metrics;

namespace TimeMachine.Engine.Storing.Impl
{
	public class MetricsStorage : IMetricsStorage, ICommitMetricsSink
	{
		private readonly IMetricsLoader loader;
		private readonly IDictionary<string, MetricStorage> storages = new Dictionary<string, MetricStorage>();
		private readonly IMetricsSaver saver;


		public MetricsStorage(IMetricsLoader loader, IMetricsSaver saver)
		{
			this.loader = loader;
			this.saver = saver;
		}

		public IEnumerable<MetricValue> GetAll(string metricId)
		{
			return Storage(metricId).GetAll();
		}

		public MetricValue GetValue(string metricId, int rev)
		{
			return Storage(metricId).GetValue(rev);
		}

		public MetricValue TryGetValue(string metricId, int rev)
		{
			return Storage(metricId).TryGetValue(rev);
		}

		public IEnumerable<string> KnownMetricIds()
		{
			return loader.KnownMetricIds();
		}

		public MetricValue FindPrevValue(string metricId, int rev)
		{
			return Storage(metricId).FindPrevValue(rev);
		}

		private MetricStorage Storage(string metricId)
		{
			return storages.GetOrCreate(
				metricId,
				() => new MetricStorage(loader, metricId, saver));
		}

		public void Take(MetricValue value)
		{
			Storage(value.MetricId).Take(value);
		}
	}

}